package com.foryou.wechat.utils;

import com.foryou.wechat.model.vo.FileVo;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

public class FileUtil {


	public static String renameToUUID(String fileName) {
		return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
	}

	public static FileVo uploadFile(String uploadPrefix,MultipartFile file) throws Exception{

		String uploadPath = file.getOriginalFilename();
		//计算文件大小
		String size = FileUtils.byteCountToDisplaySize(file.getSize());
		// 获取上传文件的后缀
		String fileSuffix = uploadPath.substring(uploadPath.lastIndexOf(".") + 1, uploadPath.length());
		// 上传文件名
		String fileName = new Date().getTime() + new Random().nextInt(100) + "." + fileSuffix;
		// 上传的文件路径
		String uploadUrl = uploadPrefix + fileName;
		File saveFile = new File(uploadUrl);
		if (!saveFile.getParentFile().exists()) {
			boolean result = saveFile.getParentFile().mkdirs();
			if (!result) {
				throw new RuntimeException("创建文件夹失败！");
			}
		}
		// TODO 将文件写入到指定目录（具体开发中有可能是将文件写入到云存储/或者指定目录通过 Nginx 进行 gzip 压缩和反向代理，此处只是为了演示故将地址写成本地电脑指定目录）
		file.transferTo(new File(uploadUrl));

		return new FileVo(size, fileName);
	}

}
